<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Foundation\Auth\AuthenticatesUsers; 
use Exception;
use Auth;
use Validator;
use Hash;
use App\User;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */

    use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/home';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest', ['except' => 'logout']);
    }

    public function username()
    {
        return 'account';
    }

    public function login(Request $request)
    {
        try{
            $this->validateLogin($request);
        } catch(Exception $e) {
            return response()->json(array('message'=>$e->getMessage(), 'code'=>400), 200);
        }
        if ($this->attemptLogin($request)) {
            $user = Auth::guard()->user();
            $user->generateToken();

            if($user->type==2 || $user->type==4){
                // 企业 九小场所
                $user->menus='startBean6,startBean9,startBean11,startBean13,startBean14,startBean5';
            }else if($user->type==3){
                // 住户
                $user->menus='startBean9,startBean11,startBean13,startBean5';
            }else if($user->type==1){
                // 后台用户
                $userinfo=User::with('menus2.menuinfo','roles.menus2.menuinfo')->findOrFail($user->id);
                $cmd1=[];
                foreach($userinfo->menus2 as $v){
                    $cmd1[]=$v->menuinfo->cmd;
                }
                $cmd2=[];
                foreach($userinfo->roles as $v){
                    foreach($v->menus2 as $v2){
                        $cmd2[]=$v2->menuinfo->cmd;
                    }
                }
                $cmd=array_unique(array_merge($cmd1,$cmd2));
                $user->menus=implode(',',$cmd);
            }

            $returnData = array();
            $returnData = $this->filterReturnLoginData($user);

            return response()->json([
                'data' => $returnData,
                'message' =>'登陆成功',
                'code' => 200
            ],200);
        }
        
        return response()->json(array('message'=>'登陆失败', 'code'=>400), 200);
    }
    protected function validateLogin(Request $request)
    {
        $account_name = $this->username();
        $rules = [
            $account_name => 'required',
            'password' => 'required',
            // 'type' => 'required'
        ];
        $messages = [
            $account_name.'.required' => '请输入账号',
            'password.required' => '请输入密码',
            // 'type.required' => '请选择登陆类型'
        ];

        $validator = Validator::make($request->all(),$rules,$messages);
        if ($validator->fails()) {
            throw new Exception($validator->errors()->first(), 1);
        }
        /*分开验证*/
        $account = $request->input($account_name);
        $password = $request->input("password");
        $type = $request->input("type");
        $user = User::where($account_name,$account)->first();
        if(empty($user)) {
            throw new Exception('账号或密码错误', 1);
        } else {
            $user = $user->makeVisible('password')->toArray();
        }
        if(!Hash::check($password , $user['password'])){
            throw new Exception('账号或密码错误', 1);
        }
        // if($user['type']!=$type) {
        //     throw new Exception('登陆类型不正确', 1);
        // }
    }

    protected function filterReturnLoginData($user)
    {
        $user = json_decode(json_encode($user), true);
        $filterFields = array("id", "name", "account", "phone", "email","work_type","api_token", "type", "companyId", "usersignature", "distinguish", "state","sex","menus");
        $returnData = array();
        foreach($filterFields as $k=>$v) {
            $returnData[$v] = $user[$v];
        }
        $returnData = unsetNull($returnData);
        if(!empty($returnData['usersignature'])) {
            $http_type = ((isset($_SERVER['HTTPS'])&&$_SERVER['HTTPS']=='on')||(isset($_SERVER['HTTP_X_FORWARDED_PROTO'])&&$_SERVER['HTTP_X_FORWARDED_PROTO']=='https'))?'https://':'http://';
            $domain = $http_type.$_SERVER['HTTP_HOST'];
            $returnData['usersignature'] = $domain.$returnData['usersignature'];
        }
        return $returnData;
    }

    // 将支持的登录字段都传递到 UserProvider 进行查询
    public function credentials(Request $request)
    {
        $credentials = $request->only($this->username(), 'password');
        return $credentials;
    }

    public function logout()
    {
        $user = Auth()->guard('api')->user();
        if($user) {
            $user->api_token = '';
            $user->save();
        }
        return response()->json(array('message'=>'退出成功', 'code'=>200), 200);
    }
}
